<template>
  <div class="searchExaminfo">
    <div v-if="$store.state.teacherInfomation">
      <!-- currentPage: 1, // 当前页码
      pageSize: 5, // 每页的数据条数 -->
      <el-table
        :data="
          tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        "
        height="500"
        border
        style="width: 100%"
      >
        <el-table-column prop="e_name" label="考试名称" width="150">
        </el-table-column>

        <el-table-column prop="eid" label="试卷编号" width="150">
        </el-table-column>

        <el-table-column prop="school" label="学校" width="150">
        </el-table-column>

        <el-table-column prop="faculty" label="院系" width="150">
        </el-table-column>

        <el-table-column prop="major" label="专业" width="150">
        </el-table-column>

        <el-table-column prop="classroom" label="班级" width="150">
        </el-table-column>

        <el-table-column
          prop="start_time"
          label="开始时间"
          width="150"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-input
              type="datetime-local"
              v-if="scope.row.isEdit"
              v-model="scope.row.start_time"
            >
            </el-input>
            <span v-else>{{ scope.row.start_time }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="end_time"
          label="结束时间"
          width="150"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-input
              type="datetime-local"
              v-if="scope.row.isEdit"
              v-model="scope.row.end_time"
            >
            </el-input>
            <span v-else>{{ scope.row.end_time }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <div class="button">
              <el-button
                :type="scope.row.isEdit ? 'success' : 'primary'"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
                >{{ scope.row.isEdit ? "保存" : "编辑" }}</el-button
              >
              <el-button
                :type="scope.row.isEdit ? 'default' : 'danger'"
                size="mini"
                @click="handleDelete(scope.$index, scope.row)"
                >{{ scope.row.isEdit ? "取消" : "删除" }}</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="block" style="margin-top: 15px">
        <el-pagination
          align="center"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[1, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
        >
        </el-pagination>
      </div>
    </div>
    <div v-else>请前往个人中心完善信息 <router-link to="/teacherHome/teacherHomepage">点击前往</router-link> </div>
  </div>
</template>
<script>
import axios from "axios";
import qs from "qs";
import { Message } from "element-ui";
export default {
  mounted() {
    this.getExaminfo();
  },
  data() {
    return {
      tableData: [{ eid: "", e_name: "", start_time: "", end_time: "" }],
      currentPage: 1, // 当前页码
      total: 20, // 总条数
      pageSize: 5, // 每页的数据条数
    };
  },
  methods: {
    //当选择每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.currentPage = 1; //从第一页开始显示
      this.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    //获取考试信息
    getExaminfo() {
      axios
        .get("/v1/teachers/examinfo")
        .then((res) => {
          if (res.data.status == 200) {
            this.tableData = res.data.data;
            // console.log(this.tableData);
            for (let a = 0; a < this.tableData.length; a++) {
              this.tableData[a].start_time = this.convertUTCTimeToLocalTime(
                this.tableData[a].start_time
              );
              this.tableData[a].end_time = this.convertUTCTimeToLocalTime(
                this.tableData[a].end_time
              );
            }
          }
        })
        .catch((err) => {});
    },
    //修改考试时间
    updateExaminfo(row) {
      axios({
        method: "put",
        url: "/v1/teachers/examtime",
        data: qs.stringify({
          ename: row.e_name,
          starttime: row.start_time,
          endtime: row.end_time,
        }),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        },
      })
        .then((result) => {
          if (result.data.status == 200) {
            Message.success({
              showClose: true,
              message: "修改成功",
              type: "success",
            });
            //更新数据
            this.getExaminfo();
          } else {
            Message.error({
              showClose: true,
              message: "修改失败",
              type: "error",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //删除考试信息
    deleteExaminfo(row) {
      axios
        .delete(`v1/teachers/deletetest/${row.e_name}`)
        .then((res) => {
          if (res.data.status == 200) {
            Message.success({
              showClose: true,
              message: "删除成功",
              type: "success",
            });
            location.reload();
          } else {
            Message.error({
              showClose: true,
              message: "删除失败",
              type: "error",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //点击编辑按钮
    handleEdit(index, row) {
      // 动态设置数据并通过这个数据判断显示方式
      if (row.isEdit) {
        // console.log("保存");
        this.updateExaminfo(row);
        //点击保存时则删除isEdit
        //  this.$delete(obj,key)
        this.$delete(row, "isEdit");
      } else {
        // console.log("编辑");
        //点击编辑时设置为true
        this.$set(row, "isEdit", true);
      }
    },

    //点击删除
    handleDelete(index, row) {
      if (row.isEdit) {
        // console.log("取消");
        this.$delete(row, "isEdit");
      } else {
        // console.log("删除");
        this.$confirm(`此操作将永久删除${row.e_name}考试, 是否继续?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            //确定删除操作
            this.deleteExaminfo(row);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    //时区转换
    convertUTCTimeToLocalTime(UTCDateString) {
      if (!UTCDateString) {
        return "-";
      }

      function formatFunc(str) {
        //格式化显示
        return str > 9 ? str : "0" + str; //如果>9则为str 否则拼接0
      }
      var date2 = new Date(UTCDateString); //这步是关键
      var year = date2.getFullYear();
      var mon = formatFunc(date2.getMonth() + 1); //月份是0-11所以要+1显示
      var day = formatFunc(date2.getDate());
      var hour = date2.getHours();
      var noon = hour >= 12 ? "PM" : "AM";
      hour = hour >= 12 ? hour - 12 : hour;
      hour = formatFunc(hour);
      var min = formatFunc(date2.getMinutes());
      var dateStr =
        year + "-" + mon + "-" + day + " " + noon + " " + hour + ":" + min;
      return dateStr;
    },
  },
};
</script>
<style lang="scss">
.searchExaminfo {
  margin: 0 auto;
  margin-top: 50px;
}
</style>